package com.codemate.interview.java;

import java.util.HashMap;
import java.util.Map;

/**
 * 本地线程
 *
 * @author hice
 * @apiNote 使用场景：比如mybatis自动注入当前用户名
 */
public class ThreadLocalDemo {

    private static final String USERNAME = "username";
    private static final ThreadLocal<Map<String, String>> THREAD_LOCAL = ThreadLocal.withInitial(
        () -> new HashMap<>(1));

    public static void put(String key, String value) {
        THREAD_LOCAL.get().put(key, value);
    }

    public static String get(String key) {
        return THREAD_LOCAL.get().get(key);
    }

    public static void remove(String key) {
        THREAD_LOCAL.get().remove(key);
    }

    public static String getUsername() {
        return get(USERNAME);
    }

    public static void setUsername(String username) {
        put(USERNAME, username);
    }

    public static void removeUsername(String key) {
        remove(USERNAME);
    }

    public static void main(String[] args) {
        // 拦截授权请求，给本地线程设置当前用户名
        setUsername("我是橙子");
        // mybatis-plus自动注入功能获取操作人
        System.out.println(getUsername());
    }

}
